<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>智能售卡系统</title>
    <!--    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">-->
    <!--    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-7ymO4nGrkm372HoSbq1OY2DP4pEZnMiA+E0F3zPr+JQQtQ82gQ1HPY3QIVtztVua" crossorigin="anonymous"></script>-->
    <link rel="stylesheet" href="../../..//public/layui/css/layui.css">
    <script src="../../..//public/layui/layui.js"></script>
<!--    <script src="../../..//public/jquery/jquery.min.js"></script>-->
<!--    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>-->
    <style>
        .fixed-top {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            line-height: 70px;
            z-index: 1000; /* 确保导航栏在页面其他内容的上方 */
            background-color: #fff; /* 根据需要设置背景颜色 */
            box-shadow: 0 2px 4px rgba(0,0,0,0.1); /* 添加一个简单的阴影效果 */
        }
        .nav-right {
            display: flex;
            align-items: center;
            list-style: none; /* Remove bullet points */
            margin: 0;
            padding-right: 5px;
            line-height: 70px;
            justify-content: right;
        }
        .product-list {
            list-style: none;
            padding: 0;
            margin-left: 45px;
            margin-right: 45px;
            display: flex;
            flex-wrap: wrap;
        }

        .product-item {
            /*width: calc(20% - 20px); !* 减去左右padding和margin 每行5个显示 *!*/
            width: calc(25% - 20px); /* 减去左右padding和margin */
            /*height: 300px; !* 明确设置li的高度，根据实际情况调整 *!*/
            padding: 10px;
            box-sizing: border-box;
            display: flex;
            /*align-items: flex-start;*/
            margin: 10px;
            border: 1px solid #ddd; /* 边框示例 */
            border-radius: 5px; /* 边框圆角示例 */
            background-color: #fff; /* 背景颜色示例 */
            align-items: stretch; /* 确保子元素占满整个高度 */
        }
        @media (max-width: 576px) {
            .product-item {
                width: calc(100% - 20px); /* 移动设备上每行只显示一个产品 */
            }
        }
        .product-image {
            flex: 1;
            padding-right: 20px; /* 图片和信息之间的间距 */
        }

        .product-image img {
            /*width: 100%;*/
            /*max-width: 200px; !* 根据需要调整图片的最大宽度 *!*/
            /*cursor: pointer;*/
            width: 100%; /* 占满容器宽度 */
            height: auto; /* 保持宽高比 */
            object-fit: cover; /* 填充容器，可能裁剪 */
        }

        .product-info {
            flex: 2; /* 确保信息区域有足够的空间 */
        }

        .product-name,
        .product-price,
        .product-description,
        .product-area {
            margin-bottom: 10px;
        }

        .product-name {
            font-size: 18px;
            font-weight: bold;
        }

        .product-price {
            font-size: 16px;
            color: #e74c3c; /* 价格颜色示例 */
        }

        .product-description {
            font-size: 14px;
        }

        .product-area {
            font-size: 14px;
            color: #7f8c8d; /* 字体颜色示例 */
        }

        .product-buy-button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px 20px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 4px 2px;
            cursor: pointer;
        }
    </style>
</head>
<body>
<!--<div class="top_nav">-->
<!--    <ul class="layui-nav layui-bg-green" lay-bar="disabled">-->
<!--        <li class="layui-nav-item"><a href=""><img src="https://www.bootcss.com/assets/img/navlogo-small.png"-->
<!--                                                   style="margin-right: 10px"/>智能售卡系统</a></li>-->
<!--        <li class="layui-nav-item"><a href="/index">首页</a></li>-->
<!--        &lt;!&ndash;    <li class="layui-nav-item"><a href="/order">订单</a></li>&ndash;&gt;-->
<!--        <li class="layui-nav-item"><a href="/phone">联系</a></li>-->
<!--        <li class="layui-nav-item"><a href="/about">关于</a></li>-->
<!--        <div  class="nav-right" style="float: right;">-->
<!--            <li class="layui-nav-item" id="login-item"><a href="/login" id="login">登录</a></li>-->
<!--            <li class="layui-nav-item" id="logout-item"><a href="javascript:void(0);" id="logout">退出</a></li>-->
<!--        </div>-->
<!--    </ul>-->
<!--</div>-->
<div class="layui-row fixed-top">
    <div class="layui-col-xs8 layui-col-sm8 layui-col-md10">
        <a href=""><img src="<?= htmlspecialchars($icon) ?>" width="50px" height="50px" style="margin-left: 10px"/><span style="margin-left: 10px"><?=htmlspecialchars($name)?></span></a>
        <a href="/index" style="margin-left: 5px">首页</a>
        <!--        <a href="/about" style="margin-left: 5px">关于</a>-->
        <a href="/help" style="margin-left: 5px">手册</a>
    </div>
    <div class="layui-col-xs4 layui-col-sm4 layui-col-md2 nav-right">
        <li class="layui-nav-item" id="login-item" style="margin-right: 4px"><a href="/login" id="login">登录</a></li>
        <li class="layui-nav-item" id="logout-item"><a href="javascript:void(0);" id="logout"><span>退出</span></a></li>
    </div>
</div>
<div style="margin-left: 40px;margin-right: 50px;margin-top: 90px">
    <blockquote class="layui-elem-quote">
        商品数据
    </blockquote>
</div>
<!--<div>-->
<!--    <div style="margin-left: 50px;margin-right: 50px;margin-top: 20px">-->
<!--        <table class="layui-table" id="productTable" lay-filter="productTable">-->
<!--            <colgroup>-->
<!--                <col width="150">-->
<!--                <col width="150">-->
<!--                <col>-->
<!--            </colgroup>-->
<!--            <thead>-->
<!--        </table>-->
<!--    </div>-->
<!--</div>-->
<div>
    <div id="productListContainer"></div>
</div>
<div style="text-align: center"><div id="demo-laypage-normal-2"></div></div>

<div id="form-container" style="display: none;">
    <form class="layui-form" lay-filter="buy-form">
        <!-- 在这里放置你的表单内容 -->
        <div class="layui-form-item">
            <label class="layui-form-label required">设备编号</label>
            <div class="layui-input-block required" style="margin-right: 30px">
                <input type="text" name="pay_phone" required lay-verify="required" placeholder="请填写监控设备编号,确保正确" autocomplete="off" class="layui-input">
            </div>
        </div>
    </form>
</div>
<!--<input type="hidden" id="apiUrl" value="<?php echo \common\UrlEnv::getUrl(); ?>">-->
<!--<input type="hidden" id="wsUrl" value="<?php echo \common\UrlEnv::getWs(); ?>">-->

<div id="pay_div_code" style="width: 350px;height: 600px;padding: 10px;display: none;">
    <div>
        <div><span style="margin-top: 10px">支付完成后，请耐心等待，若长时间无反馈，请尝试刷新浏览器观察下方订单支付结果，若出现异常，请及时联系管理员</span></div>
<!--        <div></div>-->
        <div><span>订单编号：</span><span id="order_no"></span></div>
    </div>
    <div>
        需支付金额:
        <span id="pay_price" style="font-size: 30px;color: red">支付金额:</span>
        元
        &nbsp;&nbsp;&nbsp;&nbsp;已优惠金额:
        <span id="cut_down_price" style="color: red"></span>
        元
    </div>
    <div class="pay-buttons" style="display: flex; justify-content: center; align-items: center;">
        <button id="button_pay_ali" class="layui-btn layui-btn-normal" onclick="showPayCode('ali')">支付宝</button>
        <button id="button_pay_wx" class="layui-btn layui-btn-primary" onclick="showPayCode('wx')">微&nbsp;&nbsp;&nbsp;&nbsp;信</button>
    </div>
<!--    这个是阿里收款码-->
    <img src="" alt="" id="pay_code" style="max-width: 100%; max-height: 100%;">
<!--    这个是微信收款码-->
    <img src="" alt="" id="pay_code_wx" style="max-width: 100%; max-height: 100%;display: none;">
</div>

<div id="order_div">
    <div style="margin-left: 50px;margin-right: 50px;margin-top: 20px">
        <blockquote class="layui-elem-quote">
            购买结果
        </blockquote>
    </div>
    <div style="margin-left: 50px;margin-right: 50px;margin-top: 20px">
        <table class="layui-table" id="productOrder" lay-filter="productOrder">
            <colgroup>
                <col width="150">
                <col width="150">
                <col>
            </colgroup>
            <thead>
        </table>
    </div>
    <div style="text-align: center"><div id="demo-laypage-normal-3"></div></div>
</div>

<div id="target-test" style="position: relative; padding: 10px;">
</div>
<script type="text/html" id="barBtn">
    <a class="layui-btn layui-btn-sm" lay-event="buy">购买</a>
</script>
</body>
</html>
<script>
    let clickData = {}
    let apiUrl = '<?php echo \common\UrlEnv::getUrl(); ?>';
    let wsUrl = '<?php echo \common\UrlEnv::getWs(); ?>';
    let payPhone
    let payNickName = "支付宝"
    let ws
    let order_no = ""
    let currentPage = 1
    let currentOrderPage = 1;
    let payDivCodeLayerIndex;
    let cutPrice = 0.0
    let products = []
    let isAdmin = 1

    layui.use(['table','form'],function (){
        let laypage = layui.laypage;
        let table = layui.table;
        let form = layui.form;
        let $ = layui.$;
        let util = layui.util;

        laypage.render({
            elem: 'demo-laypage-normal-3',
            count: 1000, // 数据总数
            jump: function(obj, first){
                // 首次不执行
                if(!first){
                    console.log('订单当前页：' + obj.curr);
                    currentOrderPage = obj.curr
                    //console.log('订单翻页：',currentOrderPage)
                    // 发起Ajax请求
                    queryOrder()
                }
            }
        });
        laypage.render({
            elem: 'demo-laypage-normal-2',
            count: 1000, // 数据总数
            jump: function(obj, first){
                // 首次不执行
                if(!first){
                    //console.log('产品当前页：' + obj.curr);
                    currentPage = obj.curr
                    // 发起Ajax请求
                    queryProject()
                }
            }
        });

        queryProject()

        let user_id = localStorage.getItem('user_id')
        $("#order_div").hide()
        if (user_id>0){
            queryOrder()
        }
        $(document).ready(function() {
            let username = localStorage.getItem('username');
            let loginItem = $('#login-item');
            let logoutItem = $('#logout-item');
            let loginButton = $('#login');
            let logoutButton = $('#logout');

            if (username) {
                // 用户已登录，显示用户名，隐藏登录按钮，显示退出按钮
                loginButton.text(username);
                loginButton.attr('href', 'javascript:void(0);'); // 禁止跳转登录页面
                logoutItem.show();
                loginItem.show();
            } else {
                // 用户未登录，显示登录按钮，隐藏退出按钮
                loginItem.show();
                logoutItem.hide();
            }

            layui.$('#logout').on('click', function() {
                //console.log('点击退出按钮');
                layui.$.ajax({
                    url:'/app/admin/user/logout',
                    type: "POST",
                    data: {user_id:localStorage.getItem('user_id')},
                    success:function (res) {
                        layer.msg('退出成功')
                        localStorage.removeItem('username');
                        localStorage.removeItem('token');
                        localStorage.removeItem('user_id');
                        setTimeout(function () {
                            location.reload(); // 刷新页面以更新按钮显示
                        },1500)
                    },error:function (res){

                    }
                })

            });
        });

        function queryOrder(){
            let querySelfOrder = {
                user_id:localStorage.getItem('user_id'),
                page:currentOrderPage,
                token:localStorage.getItem('token')
            }
            layui.$.ajax({
                url:'/index/query_pay_over_order',
                type:'POST',
                data:querySelfOrder,
                dataType: 'json',
                success:function (res){
                    if (user_id){
                        $("#order_div").show()
                    }
                    table.render({
                        elem: '#productOrder', // 表格DOM元素的选择器
                        data: res.data,   // 请求返回的数据数组
                        // cellMinWidth: 100, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                        cols: [[ // 表头
                            {field: 'product_name',width:128, title: '商品名称'},
                            // {field: 'pay_phone', title: '支付手机号',},
                            // {field: 'pay_nickname', title: '支付昵称'},

                            {field: 'pay_price',width:110, title: '支付金额', templet: function (d) {
                                    return d.pay_price +" 元";
                                }},
                            {
                                field: 'is_pay',width:110, title: '支付状态',templet: function (d) {
                                    return d.is_pay==1 ? '已支付': '未支付';
                                }
                            },
                            {field: 'activated_code',width: '55%',resizable: true,title: '激活码'},
                            {field: 'created_at',width:250, title: '订单时间'},
                            {field: 'pay_nickname',width:110, title: '支付方式',templet: function (d) {
                                    return d.pay_nickname;
                                }}
                        ]],
                        done: function (res, curr, count) {
                            if (res.data.length === 0) {
                                // $("#order_div").hide()
                                // 如果数据为空，则显示提示信息
                                let emptyMsg = '<div style="text-align: center; padding: 20px;">暂无订单</div>';
                                $(this.elem).next('.layui-none').html(emptyMsg);
                            }
                        }
                    });
                },
                error: function(xhr, status, error){
                    console.error('请求订单信息失败:', error);
                }
            })
        }

        /**
         * 查询在售商品
         */
        function queryProject(){
            layui.$.ajax({
                url: apiUrl+'/index/query_product',
                type: 'POST',
                data:{page:currentPage,token:localStorage.getItem('token')},
                dataType: 'json',
                success: function(res){
                    let productListContainer = layui.$('#productListContainer');
                    products = res.data;
                    let listHtml = '<ul class="product-list">'; // 开始创建列表

                    products.forEach(function(product, index) {
                        // clickData = product
                        listHtml += '<li class="product-item" data-index="' + index + '">'
                            + '<div class="product-image">'
                            // + '<img src="' + product.product_img + '" alt="' + product.product_name + '"  style="width: 100%;height: auto" onclick='showImage('{{product.product_img}}', '{{product.product_img}}')'/>'
                            +'<img src="' + product.product_img + '" alt="' + product.product_name + '" style="width: 100%;height: auto" onclick="showImage(\'' + product.product_img.replace(/'/g, '&#39;') + '\', \'' + product.product_name.replace(/'/g, '&#39;') + '\')"/>'
                            + '</div>'
                            + '<div class="product-info">'
                            + '<div class="product-name">' + product.product_name + '</div>'
                            + '<div class="product-price">商品价格：￥' + (product.product_price ? product.product_price : '未知') + '</div>'
                            + '<div class="product-description">商品描述：' + product.product_des + '</div>'
                            + '<div class="product-area">简要说明：' + product.product_shows + '</div>'
                            + '<button class="product-buy-button" onclick="toBuy(' + index + ')">购买</button>' // 购买按钮
                            + '</div>'
                            + '</li>';
                    });

                    listHtml += '</ul>'; // 结束列表
                    productListContainer.html(listHtml); // 将生成的列表HTML设置到容器中
                },
                error: function(xhr, status, error){
                    console.error('请求失败:', error);
                }
            });
        }
    })
    function toBuy(index){
        //console.log('点击的第几个',index)
        clickData = products[index]
        //console.log('输出对象结果：',clickData)
        let username = localStorage.getItem('username')
        if (!username){
            layer.msg('请先登录')
            setTimeout(function () {
                window.location.href = '/login'
            },1500)
            return
        }
        // 这里编写购买商品的逻辑，例如弹出确认框等
        layer.confirm('确定购买该商品吗？', function(index){
            // option.title='温馨提示'
            // 这里可以编写购买商品的逻辑，例如发送购买请求等
            cutPrice = 0.0
            payNickName = ""
            order_no = ""
            layer.close(index);
            layui.$.ajax({
                url:'/index/query_cut_price',
                type:'POST',
                data:{user_id:localStorage.getItem('user_id'),token:localStorage.getItem('token')},
                dataType:'json',
                success:function (res) {
                    if (res.code === 0 ){
                        cutPrice = res.data
                        // let queryPay = {
                        //     'order_no':res.data
                        // }
                        layui.$.ajax({
                            url:apiUrl+'/index/to_pay',
                            data: {'page':10000,'token':localStorage.getItem('token'),'time':Date.now()},
                            type: 'POST',
                            dataType: 'json',
                            success:function (res){
                                //console.log("获取支付二维码：",res.data,'  '+res.data.length)
                                if (res.data.length===1){
                                    document.querySelector(".pay-buttons").style.display = 'none'
                                    let bean = res.data[0]
                                    if (bean.pay_channel==="支付宝"){
                                        document.getElementById('pay_code').style.display = 'block'
                                        document.getElementById('pay_code_wx').style.display = 'none'
                                        let imageUrl = apiUrl+bean.pay_qrcode; // 替换为你的图片地址
                                        // //console.log("输出支付宝扫码地址：",imageUrl)
                                        document.getElementById("pay_code").src = imageUrl;
                                        payNickName = "支付宝"
                                    }else if (bean.pay_channel==="微信"){
                                        document.getElementById('pay_code').style.display = 'none'
                                        document.getElementById('pay_code_wx').style.display = 'block'
                                        let imageUrl = apiUrl+bean.pay_qrcode; // 替换为你的图片地址
                                        document.getElementById("pay_code_wx").src = imageUrl;
                                        // console.log("输出微信扫码地址：",imageUrl)
                                        payNickName = "微信"
                                    }
                                }else{
                                    for (let i=0;i<res.data.length;i++){
                                        let bean = res.data[i]
                                        // console.log("输出循环item:",bean)
                                        if (bean.pay_channel==="支付宝"){
                                            let imageUrl = apiUrl+bean.pay_qrcode; // 替换为你的图片地址
                                            // console.log("输出支付宝扫码地址：",imageUrl)
                                            document.getElementById("pay_code").src = imageUrl;
                                        }else if (bean.pay_channel==="微信"){
                                            let imageUrl = apiUrl+bean.pay_qrcode; // 替换为你的图片地址
                                            document.getElementById("pay_code_wx").src = imageUrl;
                                            // console.log("输出微信扫码地址：",imageUrl)
                                        }
                                    }
                                    showPayCodeUi('ali')
                                }
                                //console.log("删除最终的支付图片结果",imageUrl)
                                document.getElementById("pay_price").textContent = ""+(clickData.product_price - cutPrice).toFixed(2)
                                document.getElementById("cut_down_price").textContent = ""+cutPrice
                                let createOrder = {
                                    'order_no':order_no,
                                    'product_id':clickData.id,
                                    'product_name':clickData.product_name,
                                    // 'pay_phone':localStorage.,
                                    'pay_nickname':payNickName,
                                    'is_pay':0,
                                    'pay_price':clickData.product_price - cutPrice,
                                    'discount_price':cutPrice,
                                    'username':localStorage.getItem('username'),
                                    'token':localStorage.getItem('token'),
                                    'user_id':localStorage.getItem('user_id'),
                                }
                                layui.$.ajax({
                                    url: apiUrl+'/index/create_order',
                                    data: createOrder,
                                    type: 'POST',
                                    dataType: 'json',
                                    success:function (res) {
                                        // layer.close(loadingIndex);
                                        //console.log("输出订单创建结果：")
                                        if (res.code===0){
                                            // layer.msg('订单创建成功,请扫码支付')
                                            // alert("订单创建成功,请扫码支付\n订单编号:"+res.data)
                                            //创建订单成功后 直接 连上 websocket
                                            connectWs()
                                            order_no = res.data
                                            document.getElementById("order_no").textContent = order_no
                                            payDivCodeLayerIndex = layer.open({
                                                type: 1,
                                                title: false, // 不显示标题
                                                closeBtn: 1, // 显示关闭按钮
                                                area: ['auto', 'auto'], // 根据图片大小自动调整弹出层大小
                                                content: layui.$('#pay_div_code'),
                                                btn: ['支付完成', '取消'],
                                                yes:function (index, layero) {
                                                    order_no = ""
                                                    layui.$('#pay_div_code').hide(); // 隐藏 #form-container 区域
                                                    layer.close(index); // 关闭弹窗
                                                },
                                                btn2: function(index, layero){
                                                    // 取消按钮的回调函数
                                                    layui.$('#pay_div_code').hide();
                                                    layer.close(index); // 关闭弹窗
                                                    ws.close()
                                                },
                                                cancel:function (index,layero) {
                                                    layui.$('#pay_div_code').hide();
                                                    layer.close(index); // 关闭弹窗
                                                    ws.close()
                                                }
                                            });
                                        }else if (res.code===100){
                                            tokenOver()
                                        }else{
                                            layer.msg(res.msg)
                                        }
                                    },error: function(xhr, status, error){
                                        console.error('创建订单失败:', error);
                                        layer.msg('订单创建失败,请稍后再试')
                                    }
                                })

                            },error: function(xhr, status, error){
                                console.error('获取支付码异常:', error);
                                layer.msg('获取支付码异常,请稍后再试')
                                // $('#pay_code').hide()
                            }
                        })
                    }else if (res.code===100){
                        tokenOver()
                    }
                },error:function (res){

                }
            })
            layui.$('#form-container').hide(); // 隐藏 #form-container 区域
            layui.form.val('buy-form', {
                'pay_nickname': '', // 将姓名输入框清空
                'pay_phone': '', // 将姓名输入框清空
                // 其他表单字段也可以在这里清空
            });
        });
    }
    function tokenOver(){
        layer.msg(res.msg)
        localStorage.removeItem('username');
        localStorage.removeItem('token');
        localStorage.removeItem('user_id');
        setTimeout(function () {
            location.reload(); // 刷新页面以更新按钮显示
        },1000)
    }
    function showPayCode(type) {
        let aliCode = document.getElementById('pay_code');
        let wxCode = document.getElementById('pay_code_wx');
        let aliBtn = document.getElementById('button_pay_ali');
        let wxBtn = document.getElementById('button_pay_wx');
        if (type === 'ali') {
            aliCode.style.display = 'block';
            wxCode.style.display = 'none';
            aliBtn.classList.remove('layui-btn-normal');
            aliBtn.classList.remove('layui-btn-primary');
            wxBtn.classList.remove('layui-btn-normal');
            wxBtn.classList.remove('layui-btn-primary');

            aliBtn.classList.add('layui-btn-normal');
            wxBtn.classList.add('layui-btn-primary');

            //console.log("点击阿里")

            payNickName = "支付宝"

        } else if (type === 'wx') {
            aliCode.style.display = 'none';
            wxCode.style.display = 'block';
            aliBtn.classList.remove('layui-btn-normal');
            aliBtn.classList.remove('layui-btn-primary');
            wxBtn.classList.remove('layui-btn-normal');
            wxBtn.classList.remove('layui-btn-primary');

            aliBtn.classList.add('layui-btn-primary');
            wxBtn.classList.add('layui-btn-normal');
            //console.log("点击微信")
            payNickName = "微信"
        }
        create_order()
    }
    function showPayCodeUi(type) {
        let aliCode = document.getElementById('pay_code');
        let wxCode = document.getElementById('pay_code_wx');
        let aliBtn = document.getElementById('button_pay_ali');
        let wxBtn = document.getElementById('button_pay_wx');
        if (type === 'ali') {
            aliCode.style.display = 'block';
            wxCode.style.display = 'none';
            aliBtn.classList.remove('layui-btn-normal');
            aliBtn.classList.remove('layui-btn-primary');
            wxBtn.classList.remove('layui-btn-normal');
            wxBtn.classList.remove('layui-btn-primary');

            aliBtn.classList.add('layui-btn-normal');
            wxBtn.classList.add('layui-btn-primary');

            //console.log("点击阿里")

            payNickName = "支付宝"

        } else if (type === 'wx') {
            aliCode.style.display = 'none';
            wxCode.style.display = 'block';
            aliBtn.classList.remove('layui-btn-normal');
            aliBtn.classList.remove('layui-btn-primary');
            wxBtn.classList.remove('layui-btn-normal');
            wxBtn.classList.remove('layui-btn-primary');

            aliBtn.classList.add('layui-btn-primary');
            wxBtn.classList.add('layui-btn-normal');
            //console.log("点击微信")
            payNickName = "微信"
        }
    }


    function create_order(){
        let createOrder = {
            'order_no':order_no,
            'product_id':clickData.id,
            'product_name':clickData.product_name,
            // 'pay_phone':localStorage.,
            'pay_nickname':payNickName,
            'is_pay':0,
            'pay_price':clickData.product_price - cutPrice,
            'discount_price':cutPrice,
            'username':localStorage.getItem('username'),
            'token':localStorage.getItem('token'),
            'user_id':localStorage.getItem('user_id'),
        }
        layui.$.ajax({
            url: apiUrl+'/index/create_order',
            data: createOrder,
            type: 'POST',
            dataType: 'json',
            success:function (res) {
                if (res.code===0){
                    //创建订单成功后 直接 连上 websocket
                    //console.log('输出websocket对象',ws)
                    if (ws===null){
                        //console.log('ws === null')
                        connectWs()
                    }else{
                        //console.log('ws != null')
                        if (ws.readyState===2||ws.readyState===3){
                            //console.log('ws.readyState===2||ws.readyState===3')
                            connectWs()
                        }else{
                            //console.log('ws.readyState:=',ws.readyState)
                        }
                    }
                }else if (res.code===100){
                    tokenOver()
                }else{
                    layer.msg(res.msg)
                }
            },error: function(xhr, status, error){
                console.error('创建订单失败:', error);
                layer.msg('订单创建失败,请稍后再试')
            }
        })
    }
    function showImage(imageUrl, imageName) {
        // 弹出层的html内容，显示大图
        var html = '<div><img src="' + imageUrl + '" alt="' + imageName + '" style="max-width:100%; max-height:100%"></div>';

        // 使用layui的弹出层来显示大图
        layer.open({
            type: 1,
            title: false,
            closeBtn: 1,
            area: ['auto', 'auto'],
            content: html
        });
    }
    function isEmpty(obj) {
        if (typeof obj === 'string') {
            return obj === '';
        } else if (Array.isArray(obj)) {
            return obj.length === 0;
        } else if (typeof obj === 'object') {
            return Object.keys(obj).length === 0;
        }
        return false;
    }
    function connectWs(){
        ws = new WebSocket(wsUrl);
        ws.onopen = function (params) {
            console.log('客户端连接成功')
            let sendMsg = {
                type:'bindUserId',
                data:{
                    action:"connect",
                    user_id:localStorage.getItem('user_id'),
                    is_pay:0
                }
            }
            ws.send(JSON.stringify(sendMsg))
        };
        // 从服务器接受到信息时的回调函数
        ws.onmessage = function (e) {
            let bean = JSON.parse(e.data)
            if (bean && bean.data) {
                let message = bean.data;
                if (message.action==="ping") {
                    // layer.msg('服务器连接成功,请等待支付结果,如长时间未返回结果，请联系客服')
                }else if (message.action==='paySuccess'){
                    layui.$('#pay_div_code').hide();
                    layui.$('#pay_div_code').css('display', 'none');
                    layer.close(payDivCodeLayerIndex)
                    order_no = ""
                    setTimeout(function () {
                        layer.confirm('激活码：'+message.order.activated_code, {
                            title:'订单完成',
                            btn: ['确认','取消'],
                            end:function (){
                                console.log('确认框被关闭');
                            }
                        },function(index){
                            layer.close(index);
                            location.reload()
                        },function (index){
                            layer.close(index);
                        })
                    },1000)
                }else if (message.action ==='payFailed'){
                    alert('支付失败,请联系客服')
                }
            }
        };
        // 连接关闭后的回调函数
        ws.onclose = function(evt) {
            console.log("关闭客户端连接");
        };
        // 连接失败后的回调函数
        ws.onerror = function (evt) {
            console.log("连接失败了");
        };
    }


</script>
